<template>
  <div class="ctlList-root mc-table">
    <lark-card border :radius="false" :show-title="false" body-width="60vw" body-height="30vh">
      <div class="ctlList-body">
        <div class="ctlList-body-header">
          <div class="ctlList-body-header-tabs">
            <btn-tabs @change="tabsChange" :items="tabsItems"></btn-tabs>
          </div>
          <div class="ctlList-body-header-operation">
            <el-button size="mini" type="success" @click="addBtn">新增</el-button>
            <!--            <el-button size="mini" type="success">导出</el-button>-->
            <div class="ctlList-body-header-close" @click="closeAction">
              <i class="el-icon-error"></i>
            </div>
          </div>
        </div>
        <div class="ctlList-body-list">
          <div class="ctlList-body-table" id="ctlList-body-table">
            <!-- 种质 -->
            <zz-table v-if="tabs == 1" @rowClick="zzRowClick" :table-data="tableData"></zz-table>
            <bb-table v-if="tabs == 2 " @rowClick="bbRowClick" :table-data="tableData"></bb-table>

            <zz-table v-if="tabs == 3" @rowClick="zzRowClick" :table-data="tableData"></zz-table>

            <zz-table v-if="tabs == 4" @rowClick="zzRowClick" :table-data="tableData"></zz-table>
          </div>
          <div class="ctlList-body-pagination">
            <el-pagination
              small
              layout="prev, pager, next"
              :total="pageInfo.total"
              :current-page="pageInfo.pageNum"
              :page-size="pageInfo.pageSize"
              @current-change="pageChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </lark-card>


    <lark-card border :x="500" :y="100" body-height="600px" :body-width="'500px'" v-if="editTaskVisible"
               :hidden="!editTaskVisible"
               @closeAction="editTaskVisible = !editTaskVisible"
               card-title="新增采集信息" draggable
               :radius="false">
      <el-scrollbar>
        <div class="edit-caiji-body" style="padding: 10px 5px">
          <el-form ref="edit-ctl-result-form" :rules="rules" :model="editDataForm" label-width="80px">
            <el-form-item label="种植编号" prop="germplasmId">
              <el-input v-model="editDataForm.germplasmId"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="cltType">
              <el-select v-model="editDataForm.cltType" placeholder="请选择">
                <el-option
                  v-for="item in tabsItems"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采集时间" prop="collectionTime">
              <el-date-picker type="datetime" v-model="editDataForm.collectionTime"
                              value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
            <el-form-item label="采集任务" prop="taskId">
              {{ taskName }}
              <el-button @click="selectTaskVisible = true" size="small">选择任务</el-button>
            </el-form-item>
            <el-form-item label="采集人" prop="users">


              <div class="u-l-container"
                   v-if="editDataForm && editDataForm.users && Array.isArray(editDataForm.users) && editDataForm.users.length > 0">
                <el-scrollbar>
                  <el-tag
                    style="margin-right: 5px"
                    v-for="user in editDataForm.users"
                    :key="user.userName"
                    closable
                    type="info"
                    @close="userRemove(user)">
                    {{ user.nickName }}
                  </el-tag>
                </el-scrollbar>
              </div>


              <el-button @click="selectUserVisible = true" size="small">选择采集人</el-button>
            </el-form-item>
            <el-form-item label="采集地点" prop="location">
              <el-input v-model="editDataForm.location"></el-input>
            </el-form-item>
            <el-form-item label="行政区划" prop="areaCode">
              <area-select @change="areaValChange"></area-select>
            </el-form-item>

            <el-form-item label="经度" prop="longitude">
              <el-input type="number" v-model="editDataForm.longitude"></el-input>
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input type="number" v-model="editDataForm.latitude"></el-input>
            </el-form-item>
            <el-form-item label="海拔" prop="elecation">
              <el-input type="number" v-model="editDataForm.elecation"></el-input>
            </el-form-item>
            <el-form-item label="坡度" prop="slopeDegree">
              <el-input type="number" v-model="editDataForm.slopeDegree"></el-input>
            </el-form-item>
            <el-form-item label="坡向" prop="slopeAcepect">
              <el-input v-model="editDataForm.slopeAcepect"></el-input>
            </el-form-item>
            <el-form-item label="坡位" prop="slopePosition">
              <el-input v-model="editDataForm.slopePosition"></el-input>
            </el-form-item>
            <el-form-item label="地形" prop="topography">
              <el-input v-model="editDataForm.topography"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="count">
              <el-input type="number" v-model="editDataForm.count"></el-input>
            </el-form-item>
            <el-form-item label="生境" prop="niche">
              <el-input v-model="editDataForm.niche"></el-input>
            </el-form-item>
            <el-form-item label="伴生种" prop="associateSpecies">
              <el-input v-model="editDataForm.associateSpecies"></el-input>
            </el-form-item>
            <el-form-item v-show="editDataForm.cltType == 2" label="颜色">
              <el-input v-model="editDataForm.color"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="editDataForm.remark"></el-input>
            </el-form-item>

            <el-form-item label="根照片" prop="picG">
              <upload-image :limit="1" v-model="editDataForm.picG"></upload-image>
            </el-form-item>
            <el-form-item label="茎照片" prop="picJ">
              <upload-image :limit="1" v-model="editDataForm.picJ"></upload-image>
            </el-form-item>
            <el-form-item label="叶照片" prop="picY">
              <upload-image :limit="1" v-model="editDataForm.picY"></upload-image>
            </el-form-item>
            <el-form-item label="花照片" prop="picH">
              <upload-image :limit="1" v-model="editDataForm.picH"></upload-image>
            </el-form-item>
            <el-form-item label="全株照片" prop="picQZ">
              <upload-image :limit="1" v-model="editDataForm.picQZ"></upload-image>
            </el-form-item>
            <el-form-item label="生境照片" prop="picSJ">
              <upload-image :limit="1" v-model="editDataForm.picSJ"></upload-image>
            </el-form-item>


          </el-form>
          <div class="edit-caiji-submit">
            <el-button @click="saveBtn">保存</el-button>
          </div>
        </div>
      </el-scrollbar>
    </lark-card>

    <lark-card border card-title="选择采集任务" :x="500" :radius="false" v-if="selectTaskVisible" :hidden="!selectTaskVisible"
               body-width="700px" body-height="570px"
               @closeAction="selectTaskVisible = !selectTaskVisible" draggable>
      <div class="select-task-body">
        <task-select @selectData="selectData"></task-select>
      </div>
    </lark-card>


    <lark-card border card-title="选择采集人" :x="500" :radius="false" v-if="selectUserVisible" :hidden="!selectUserVisible"
               body-width="700px" body-height="550px"
               @closeAction="selectUserVisible = !selectUserVisible" draggable>
      <div class="select-user-body">
        <user-select v-model="editDataForm.users"></user-select>
        <div style="width: 100%;text-align: right;padding-right:20px">
          <el-button @click="selectUserVisible = false">确定</el-button>
        </div>
      </div>
    </lark-card>

  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, watch, computed } from '@vue/composition-api'
  import btnTabs from '@/components/ServiceComponents/btnTabs'
  import zzTable from '@/views/industry/clt/ctlList/zzTable'
  import bbTable from '@/views/industry/clt/ctlList/bbTable'
  import loading from '@/utils/loading'
  import { resultByTaskId, addResult, resultList } from '@/api/industry/ctl'
  import taskSelect from '@/views/industry/clt/ctlList/taskSelect'
  import UploadImage from '@/components/UploadImage'
  import userSelect from '@/components/ServiceComponents/userSelect'
  import areaSelect from '@/components/ServiceComponents/areaSelect'
  import AreaSelect from '@/components/ServiceComponents/areaSelect/index'
  import { baseValidate } from '@/utils/elementValidate'

  export default {
    name: 'ctlList',
    components: {
      AreaSelect,
      userSelect,
      UploadImage,
      taskSelect,
      btnTabs,
      zzTable,
      bbTable
    },
    props: {},
    setup(props, content) {
      let data = reactive({
        rules: {
          germplasmId: [
            { name: '种植编号', min: 1, max: 30, validator: baseValidate, require: true, trigger: 'blur' }
          ],//null,//种植编号
          cltType: [
            { required: true, message: '类型不能为空', trigger: 'blur' }
          ],//null,//类型
          collectionTime: [
            { required: true, message: '采集时间不能为空', trigger: 'blur' }
          ],//null,//采集时间
          longitude: [
            { required: true, message: '经度不能为空', trigger: 'blur' }
          ],// null,//经度
          latitude: [
            { required: true, message: '纬度不能为空', trigger: 'blur' }
          ],// null,//维度
          elecation: [
            { required: true, message: '海拔不能为空', trigger: 'blur' }
          ],// null,//海拔
          slopeDegree: [
            { required: true, message: '坡度不能为空', trigger: 'blur' }
          ],// null,//坡度
          slopeAcepect: [
            { required: true, message: '坡向不能为空', trigger: 'blur' }
          ],//null,//坡向
          slopePosition: [
            { required: true, message: '坡位不能为空', trigger: 'blur' }
          ],//null,//坡位
          topography: [
            { name: '地形', min: 1, max: 20, validator: baseValidate, require: true, trigger: 'blur' }
          ],// null,//地形
          remark: [],//null,//备注
          taskId: [
            { required: true, message: '采集任务不能为空', trigger: 'blur' }
          ],//null, //采集任务
          count: [
            { name: '数量', min: 1, max: 100000, validator: baseValidate, require: true, trigger: 'blur' }
          ],// null,//数量
          niche: [
            { name: '生境', min: 1, max: 30, validator: baseValidate, require: true, trigger: 'blur' }
          ],//null,//生境
          associateSpecies: [
            { name: '伴生种', min: 1, max: 30, validator: baseValidate, require: true, trigger: 'blur' }
          ],//null, //伴生种
          color: [],// null,
          users: [
            { type: 'array', required: true, message: '至少有一个采集人', trigger: 'change' }
          ],//[],
          areaCode: [
            { required: true, message: '行政区划', trigger: 'blur' }
          ],//[],
          location: [
            { name: '采集地点', min: 1, max: 100, validator: baseValidate, require: true, trigger: 'blur' }
          ],//''//采集地点

          picG: [
            { type: 'array', name: '根照片', require: true, validator: baseValidate, trigger: 'blur' }
          ],
          picJ: [
            { type: 'array', name: '茎照片', require: true, validator: baseValidate, trigger: 'blur' }
          ],
          picY: [
            { type: 'array', name: '叶照片', require: true, validator: baseValidate, trigger: 'blur' }
          ],
          picH: [
            { type: 'array', name: '花照片', require: true, validator: baseValidate, trigger: 'blur' }
          ],
          picQZ: [
            { type: 'array', name: '全株照片', require: true, validator: baseValidate, trigger: 'blur' }
          ],
          picSJ: [
            { type: 'array', name: '生境照片', require: true, validator: baseValidate, trigger: 'blur' }
          ]
        },
        arr: [],
        taskId: null,
        tableData: [],
        tabsItems: [{ name: '种子', value: 1 }, { name: '标本', value: 2 }, { name: '土壤', value: 3 }, {
          name: '水分',
          value: 4
        }],
        editTaskVisible: false,
        selectTaskVisible: false,
        selectUserVisible: false,
        taskName: '',
        editDataForm: {
          germplasmId: null,//种植编号
          cltType: null,//类型
          collectionTime: null,//采集时间
          longitude: null,//经度
          latitude: null,//维度
          elecation: null,//海拔
          slopeDegree: null,//坡度
          slopeAcepect: null,//坡向
          slopePosition: null,//坡位
          topography: null,//地形
          remark: null,//备注
          taskId: null, //采集任务
          count: null,//数量
          niche: null,//生境
          associateSpecies: null, //伴生种
          color: null,
          // imagePath: [],根，茎，叶，花，全株，生境
          picG: [],
          picJ: [],
          picY: [],
          picH: [],
          picQZ: [],
          picSJ: [],

          users: [],
          areaCode: null,//行政区划
          location: ''//采集地点

        },
        pageInfo: {
          total: 0,
          pageNum: 1,
          pageSize: 5
        },
        tabs: 1,
        inputSearchForm: {
          endDate: null,
          location: null,
          startDate: null,
          value: null
        }
      })

      //种质表格行点击事件
      const zzRowClick = ({ row, column, event }) => {
        content.emit('rowClick', row.id)
        console.log(row, column, event)
      }
      const bbRowClick = ({ row, column, event }) => {
        content.emit('rowClick', row.id)
        console.log(row, column, event)
      }

      const pageChange = async(currentPage) => {
        data.pageInfo.pageNum = currentPage
        await loadListData()
      }

      const areaValChange = (val) => {
        data.editDataForm.areaCode = val[val.length - 1]
      }

      const loadListData = async() => {
        //    let load = loading(document.getElementById('ctlList-body-table'))
        try {
          let response
          let pageInfo = JSON.parse(JSON.stringify(data.pageInfo))
          delete pageInfo.total
          if (data.taskId != null) {
            response = await resultByTaskId({ taskId: data.taskId, taskType: data.tabs, ...pageInfo })

          } else {
            response = await resultList({ ...data.inputSearchForm, ...pageInfo, type: data.tabs })
          }

          //通知父组件。渲染地图
          content.emit('dataLoaded', response.rows)

          data.tableData = response.rows
          data.pageInfo.total = response.total
        } finally {
          //   load.close()
        }
      }

      const userRemove = (user) => {

        data.editDataForm.users = data.editDataForm.users.filter(item => item.userId !== user.userId)

        data.editDataForm = JSON.parse(JSON.stringify(data.editDataForm))

      }

      const selectData = (item) => {
        data.taskName = item.taskName
        data.editDataForm.taskId = item.id
        data.selectTaskVisible = false
      }

      onMounted(async() => {
      })

      const resetEditForm = () => {
        data.editDataForm = {
          germplasmId: null,//种植编号
          cltType: null,//类型
          collectionTime: null,//采集时间
          longitude: null,//经度
          latitude: null,//维度
          elecation: null,//海拔
          slopeDegree: null,//坡度
          slopeAcepect: null,//坡向
          slopePosition: null,//坡位
          topography: null,//地形
          remark: null,//备注
          taskId: null, //采集任务
          count: null,//数量
          niche: null,//生境
          associateSpecies: null, //伴生种
          color: null,
          // imagePath: [],
          users: [],
          location: null,
          areaCode: null,
          picG: [],
          picJ: [],
          picY: [],
          picH: [],
          picQZ: [],
          picSJ: []
        }
      }

      const addBtn = () => {
        //重置表单
        data.taskName = ''
        resetEditForm()
        data.editTaskVisible = true
      }

      const saveBtn = async() => {

        //    let load = loading(document.getElementById('ctlTask-list'))
        content.refs['edit-ctl-result-form'].validate(async(valid) => {
          if (valid) {
            try {
              let requestData = JSON.parse(JSON.stringify(data.editDataForm))
              requestData.imagePath = [
                { type: 0, ...data.editDataForm.picG[0] },
                { type: 1, ...data.editDataForm.picJ[0] },
                { type: 2, ...data.editDataForm.picY[0] },
                { type: 3, ...data.editDataForm.picH[0] },
                { type: 4, ...data.editDataForm.picQZ[0] },
                { type: 5, ...data.editDataForm.picSJ[0] }
              ]
              if (requestData.cltType != 2) {
                delete requestData.color
              }
              await addResult(data.editDataForm.cltType, requestData)
              data.pageInfo.pageNum = 1
              await loadListData()
              data.editTaskVisible = false
            } finally {
              // load.close()
            }

          }
        })

      }

      const taskQuery = async(item) => {
        data.taskId = item.id
        await loadListData()
      }

      const inputQuery = async(item) => {
        console.log('item', item)
        data.taskId = null
        if (item.location) {
          data.inputSearchForm.location = item.location[item.location.length - 1]
        }
        data.inputSearchForm.endDate = item.endDate
        data.inputSearchForm.startDate = item.startDate
        data.inputSearchForm.value = item.value
        await loadListData()
      }

      const tabsChange = async(item) => {
        data.tabs = item.value
        data.pageInfo.pageNum = 1
        await loadListData()
      }

      const closeAction = () => {
        content.emit('closeSelfAction')
      }

      return {
        ...toRefs(data),
        closeAction,
        pageChange,
        addBtn,
        saveBtn,
        taskQuery,
        tabsChange,
        selectData,
        inputQuery,
        zzRowClick,
        userRemove,
        bbRowClick,
        areaValChange
      }
    }
  }
</script>

<style scoped lang="scss">
  $header-height: 20px;
  .ctlList-root {
    .ctlList-body {
      padding: 2px 2px 10px 10px;

      .ctlList-body-header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        height: $header-height;
        box-sizing: border-box;

        .ctlList-body-header-tabs {
        }

        .ctlList-body-header-operation {
          display: flex;
        }

        .ctlList-body-header-close {
          margin-left: 20px;
          font-size: 20px;
          color: red;

          &:hover {
            cursor: pointer;
          }
        }
      }

      .ctlList-body-list {
        .ctlList-body-table {
          height: calc(30vh - 50px);
        }

        .ctlList-body-pagination {

        }
      }

    }

  }
</style>
<style lang="scss">
  .select-task-body {
    padding: 20px;
  }

  .edit-caiji-body {
    position: relative;

    .el-form-item {
      .el-form-item__content {
        .el-button {
          border-radius: 25px;
        }
      }
    }

    .u-l-container {
      height: 100px;
      max-height: 100px;
    }

    .edit-caiji-submit {
      text-align: right;
      margin-right: 20px;
    }
  }

  .ctlList-root {
    .ctlList-body {
      .ctlList-body-header {
        .ctlList-body-header-operation {
          .el-button.el-button--success.el-button--mini {
            padding-top: 5px;
            padding-bottom: 5px;
          }
        }
      }


    }

  }
</style>
